// pages/login/login.js
let wcache = require("../../utils/wcache.js");
let base64encode = require("../../utils/base64.js");
var urlPath = getApp().globalData.url;
var app = getApp();

Page({
  data: {
    // username: "admin",
    // _username: "admin",
    // password: "admin",
    // _password: "admin",
    username: "",
    _username: "",
    password: "",
    _password: "",
    error: ""
  },

  onLoad: function () {

  },


  bindUsernameInput: function (e) {
    this.setData({
      username: e.detail.value,
      _username: e.detail.value
    })
  },
  bindPasswordInput: function (e) {
    this.setData({
      password: e.detail.value,
      _password: e.detail.value
    })
  },
  // 验证token(登录)
  isLogin: function () {
    var that = this;
    for (var i = 0; i < 3; i++) {
      that.setData({
        username: base64encode.base64encode(that.data.username),
        password: base64encode.base64encode(that.data.password)
      })
    }
    wx.request({
      url: urlPath + 'ztjk/sys/login',
      data: {
        username: that.data.username,
        password: that.data.password,
        captcha: "180808",
        uuid: "18697129-1401-4736-83e9-47ebb5e1a58b"
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
        console.log(res);
        if (res.data.code == 0 && res.data.username != "admin") {
          wx.setStorageSync('username', that.data.username);
          wcache.put('token', res.data.token, 604800)//拿到后将token存入全局变量  以便其他页面使用
          wcache.put('name', res.data.name, 604800)//拿到后将token存入全局变量  以便其他页面使用
          wcache.put('username', res.data.username, 604800)//拿到后将token存入全局变量  以便其他页面使用
          
          // wx.switchTab({
          //   url: "/pages/turn/turn",
          // });
          wx.reLaunch({
            url: "/pages/index/index",
          });
        } else if (res.data.username == "admin") {
          wx.setStorageSync('username', that.data.username);
          wcache.put('token', res.data.token, 604800)//拿到后将token存入全局变量  以便其他页面使用
          wcache.put('name', res.data.name, 604800)//拿到后将token存入全局变量  以便其他页面使用
          wcache.put('username', res.data.username, 604800)//拿到后将token存入全局变量  以便其他页面使用
          // wx.redirectTo({
          //   url: "/pages/index/index",
          // });
          wx.reLaunch({
            url: "/pages/index/index",
          });
        }else {
          that.setData({
            username: that.data._username,
            password: that.data._password
          })
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  }
})